package cm.tl.pms.util.assistant;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;

import java.util.*;

/**
 * @author w7h1te-ywq
 * @version 8月...
 * @date 23/8/2023 上午 10:07
 */
@Log4j2
public class ParseResultUtil {
    public static void main(String[] args) {
        String jsonStr = "[{\"特征名\":\"工单内容\",\"特征值\":\"已结案\"},{\"特征名\":\"数量\",\"特征值\":\"\"}]";
        Object jsonObject = JSON.parse(jsonStr);
        System.out.print(jsonObject);

//        String  testInText = "很抱歉，由于我无法获取实时的水费价格信息，也无法访问当地的供水部门网站，因此无法为您提供具体的水费价格信息。建议您可以直接联系当地的供水部门";
        /*
        List<String>  tstStr = new ArrayList<>();
        tstStr.add("理财");
        tstStr.add("POS");
        tstStr.add("交易限额");
//微信银行, 查询, 明细
//        tstStr = ParseResultUtil.bubbleSort(tstStr);
//        tstStr = ParseResultUtil.repeatSubStr(tstStr);
//        tstStr = repeatSort("abcdefghi",tstStr);
        String[] arr = tstStr.toArray(new String[tstStr.size()]);
//        String sortRslt = toBehandSort(arr,"查询");
        String sortRslt =  mergeKey(arr,"理财","POS");
//        String sortRslt =  delKey(arr,"查询");
//        String sortRslt =  exchange(arr,"查询","POS1");
        System.out.println(sortRslt);
         */
    }

    /**
     * 定向解析 外部格式
     *
     * @param jsonStr
     * @return
     */
    public static String afterHandle(String jsonStr) {
//        // 去除```json```前缀
        jsonStr = jsonStr.replace("```json", "").replace("```", "");

        if (isJson(jsonStr) && jsonStr.contains("{") && jsonStr.contains("}")) {
            // 是有效JSON
            //log.info("{初步解析} json: " + jsonStr);
            // 解析JSON字符串
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
            // 遍历key-value
            jsonObject.entrySet().forEach(entry -> {
                String key = entry.getKey();
                String value = entry.getValue().toString();
//                log.info("{解析成功}  key= " + key + ",value= " + value);
            });
            //log.info("{解析成功}  条数: " + jsonObject.entrySet().size());
        } else {
//            jsonStr = jsonStr.replace("[", "").replace("]","");

            log.info("{非json格式} : " + jsonStr);
        }
        return jsonStr;
    }


    public static boolean isJson(String text) {
        try {
            JSONUtil.parse(text);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String subJson(String text) {
        int start = text.indexOf('{');
        int end = text.lastIndexOf('}');
        if (start != -1 && end != -1 && end > start) {
            return text.substring(start, end + 1);
        }
        return text;
    }

    public static String getSelRslt(String text) {
        int start = text.indexOf('(');
        int end = text.lastIndexOf(')');
        if (start != -1 && end != -1 && end > start) {
            return text.substring(start + 1, end);
        }
        return text;
    }

    /**
     * 冒泡排序 (按照String 长度)
     *
     * @param inListA
     * @return
     */
    public static List<String> bubbleSort(List<String> inListA) {
        String[] arr = inListA.toArray(new String[inListA.size()]);
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            // 每轮遍历将最大的数移到末尾
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j].length() < arr[j + 1].length()) {
                    String temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return Arrays.asList(arr);
    }

    /**
     * 去重 (String 包含)
     *
     * @param inListA
     * @return
     */
    public static List<String> repeatSubStr(List<String> inListA) {
        HashMap resultMap = new HashMap<>();
        for (String data : inListA) {
            String key = data;
            String value = data;
            resultMap.put(key, value);
        }

        //
        int n = inListA.size();
        for (int i = 0; i < n; i++) {
            String ordStr = inListA.get(i);
            // 每轮遍历将最大的数移到末尾
            for (int j = i + 1; j < n; j++) {
                String matchStr = inListA.get(j);
                if (ordStr.contains(matchStr)) {
                    resultMap.remove(matchStr);
                }
            }
        }

        //返回去重后的记录
        List<String> repeatRslt = new ArrayList<>(resultMap.keySet());
        return repeatRslt;
    }

    /**
     * 将指定  字符排序到 尾部
     *
     * @param allKeywds 所有关键字 数组
     * @param tailStr   需要放置  尾部的关键字
     * @return
     */
    public static String toTailSort(String[] allKeywds, String tailStr) {

        int n = allKeywds.length;
        for (int i = 0; i < n; i++) {
            // 每轮遍历将最大的数移到末尾
            for (int j = 0; j < n - i - 1; j++) {
                if (allKeywds[j].equals(tailStr)) {
                    String temp = allKeywds[j];
                    allKeywds[j] = allKeywds[j + 1];
                    allKeywds[j + 1] = temp;
                }
            }
        }

        //重新组织
        String outStr = "";
        for (int i = 0; i < allKeywds.length; i++) {
            if (i == 0) {
                outStr = allKeywds[i];
            } else {
                outStr += "," + allKeywds[i];
            }
        }

        return outStr;
    }

    /**
     * 将指定  字符排序到 尾部
     *
     * @param allKeywds   所有关键字 数组
     * @param exchangeStr 需要放置  后面的关键字
     * @return
     */
    public static String toBehandSort(String[] allKeywds, String exchangeStr) {

        int n = allKeywds.length;
        for (int i = 0; i < n; i++) {
            if (allKeywds[i].trim().equals(exchangeStr)) {
                String temp = allKeywds[i + 1];
                allKeywds[i + 1] = allKeywds[i];
                allKeywds[i] = temp;
                break;
            }
        }

        //重新组织
        String outStr = "";
        for (int i = 0; i < allKeywds.length; i++) {
            if (i == 0) {
                outStr = allKeywds[i].trim();
            } else {
                outStr += "," + allKeywds[i].trim();
            }
        }

        return outStr;
    }

    public static String delKey(String[] allKeywds, String delStr) {
        List<String> inListA = Arrays.asList(allKeywds);

        LinkedHashMap resultMap = new LinkedHashMap<>();
        for (String data : inListA) {
            String key = data;
            String value = data;
            resultMap.put(key, value);
        }

        //
        int n = inListA.size();
        for (int i = 0; i < n; i++) {
            String ordStr = inListA.get(i);
            // 每轮遍历将最大的数移到末尾
            if (ordStr.trim().equals(delStr)) {
                resultMap.remove(delStr);
            }
        }

        //返回删除后的记录
        List<String> delrslt = new ArrayList<>(resultMap.keySet());

        //重新组织
        String outStr = "";
        for (int i = 0; i < delrslt.size(); i++) {
            if (i == 0) {
                outStr = delrslt.get(i).trim();
            } else {
                outStr += "," + delrslt.get(i).trim();
            }
        }

        return outStr;
    }

    /**
     * 合并两个关键字
     *
     * @param allKeywds
     * @param mergeB
     * @param mergeA
     * @return
     */
    public static String mergeKey(String[] allKeywds, String mergeB, String mergeA) {
        List<String> inListA = Arrays.asList(allKeywds);

        LinkedHashMap resultMap = new LinkedHashMap<>();
        for (String data : inListA) {
            String key = data.trim();
            String value = data.trim();
            resultMap.put(key, value);
        }


        //
        int n = inListA.size();
        for (int i = 0; i < n; i++) {
            String ordStr = inListA.get(i);
            // 每轮遍历将最大的数移到末尾   resultMap.get(mergeA)!=null  外层通过contains 判断有误差
            if (ordStr.trim().equals(mergeB) && resultMap.get(mergeA) != null) {
                String mergeRslt = ordStr + mergeA;
                resultMap.put(ordStr, mergeRslt);
                resultMap.remove(mergeA);
            }
        }

        //返回删除后的记录
        List<String> mergerslt = new ArrayList<>(resultMap.values());

        //重新组织
        String outStr = "";
        for (int i = 0; i < mergerslt.size(); i++) {
            if (i == 0) {
                outStr = mergerslt.get(i).trim();
            } else {
                outStr += "," + mergerslt.get(i).trim();
            }
        }
        return outStr;
    }


    /**
     * 两个关键字交互位置
     *
     * @param allKeywds
     * @param keywordBef
     * @param keywordAft
     * @return
     */
    public static String exchange(String[] allKeywds, String keywordBef, String keywordAft) {

        int n = allKeywds.length;
        for (int i = 0; i < n - 1; i++) {
            if (allKeywds[i].trim().equals(keywordBef) && allKeywds[i + 1].trim().equals(keywordAft)) {
                String temp = allKeywds[i + 1];
                allKeywds[i + 1] = allKeywds[i];
                allKeywds[i] = temp;
                break;
            }
        }

        //重新组织
        String outStr = "";
        for (int i = 0; i < allKeywds.length; i++) {
            if (i == 0) {
                outStr = allKeywds[i].trim();
            } else {
                outStr += "," + allKeywds[i].trim();
            }
        }

        return outStr;
    }

    /**
     * 将业务问 关键子树 组织成  树路径格式的要求
     *
     * @param inKeyWords
     * @return
     */
    public static String changeBusiKeysT(String inKeyWords) {
        if (inKeyWords != null && !"[]".equals(inKeyWords.trim())) {
            //获取关键字树
            inKeyWords = inKeyWords.replaceAll("\\[", "")
                    .replaceAll("\\]", "").replaceAll(" ", "")
                    .replaceAll(", ", ",");
            return inKeyWords;
        }
        return null;
    }


}
